package com.zbkj.common.utils.oss;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;

@Component
public class OSSUtil {


    @Resource
    OSSConfig ossConfig;

    public static OSSUtil ossUtil;


    @PostConstruct
    public void init() {
        ossUtil = this;
    }

    //获取OSSClient实例
    private static OSSClient getOSSClient() {
        OSSClient ossClient = new OSSClient(ossUtil.ossConfig.getEndpoint(), ossUtil.ossConfig.getAccessKeyId(), ossUtil.ossConfig.getAccessKeySecret());
        return ossClient;
    }


    /**
     * 测试上传excel
     *
     * @param myFile
     * @param key
     * @return
     * @throws FileNotFoundException
     */
    public static String uploadExcelFile(InputStream os, String key) {
        try {
            OSSClient ossClient = getOSSClient();
            key = key + new Date().getTime() + ".xls";
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
            ossClient.putObject(ossUtil.ossConfig.getBucketName(), "file/" + df.format(new Date()) + "/" + key, os);
            ossClient.shutdown();
            return "http://zimijob.oss-cn-beijing.aliyuncs.com/file/" + df.format(new Date()) + "/" + key;
        } catch (Exception e) {

        }
        return null;
    }

    //下载文件
    public static void downFile() {
        OSSClient ossClient = getOSSClient();
        ossClient.getObject(new GetObjectRequest(ossUtil.ossConfig.getBucketName(), "config.json"),
                new File("config.json"));
        ossClient.shutdown();
    }

    //文件流上传
    public static String uploadFile(MultipartFile myFile, String key) throws FileNotFoundException {
        try {

            //MultipartFile myFile =null;
            OSSClient ossClient = getOSSClient();
            // 上传文件流
            //InputStream inputStream = new FileInputStream(fileName);
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
            ossClient.putObject(ossUtil.ossConfig.getBucketName(), "file/" + df.format(new Date()) + "/" + key, myFile.getInputStream());
            // 关闭client
            ossClient.shutdown();
            return "http://zimijob.oss-cn-beijing.aliyuncs.com/file/" + df.format(new Date()) + "/" + key;

        } catch (Exception e) {

        }
        return null;
    }

    // MultipartFile方式上传
    public static String uploadPic(MultipartFile file, String key) throws IOException {
        OSSClient ossClient = getOSSClient();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
        ossClient.putObject(ossUtil.ossConfig.getBucketName(), "venusImage/" + df.format(new Date()) + "/" + key, file.getInputStream());
        ///获取
        // 有效期
        Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 100);
        URL generatePresignedUrl = ossClient.generatePresignedUrl(ossUtil.ossConfig.getBucketName(), key, expiration);
        System.err.println("获取文件:" + generatePresignedUrl.toString());
        ossClient.shutdown();
        return "http://zimijob.oss-cn-beijing.aliyuncs.com/venusImage/" + df.format(new Date()) + "/" + key;
    }

    public static String uploadImgBase64(String base64) throws IOException {
        try {
            MultipartFile file= OSSUtil.base64ToMultipart(base64);
            String contentType = file.getContentType();
            String fileName = file.getOriginalFilename();
            String newFileName = fileName;
            System.out.println("fileName-->" + newFileName);
            System.out.println("getContentType-->" + contentType);
            String filePath = "C:\\test/";
            System.out.println(filePath);
            String key = OSSUtil.uploadPic(file,newFileName);
            System.out.println(key+"---------");
            if(key==null){
                return null;
            }
            return key;
        }catch (Exception e){
            //return ResponseResult.build(400, "上传失败!", "");
        }
        return null;
    }
    /**
     * 上传 视频
     *
     * @param key
     */
    public static String uploadVideo(InputStream in, String key) {
        OSSClient ossClient = getOSSClient();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
        ossClient.putObject(ossUtil.ossConfig.getBucketName(), "venusVideo/" + df.format(new Date()) + "/" + key, in);
        Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 100);
        URL generatePresignedUrl = ossClient.generatePresignedUrl(ossUtil.ossConfig.getBucketName(), key, expiration);
        System.err.println("获取文件:" + generatePresignedUrl.toString());
        ossClient.shutdown();
        return "http://zimijob.oss-cn-beijing.aliyuncs.com/venusVideo/" + df.format(new Date()) + "/" + key;
    }


    // 删除文件
    public static void deleteFile(String key) {

        // 创建OSSClient实例
        OSSClient ossClient = getOSSClient();
        // 删除Object
        ossClient.deleteObject(ossUtil.ossConfig.getBucketName(), key);
        // 关闭client
        ossClient.shutdown();

    }

    //获取存储对象的名字
    public static void listObject() {
        OSSClient ossClient = getOSSClient();
        // 获取指定bucket下的所有Object信息
        ObjectListing listing = ossClient.listObjects(ossUtil.ossConfig.getBucketName());

        // 遍历所有Object
        for (OSSObjectSummary objectSummary : listing.getObjectSummaries()) {
            System.out.println(objectSummary.getKey());
        }
    }

    public static MultipartFile base64ToMultipart(String base64) {
        try {
            String[] baseStrs = base64.split(",");

            BASE64Decoder decoder = new BASE64Decoder();
            byte[] b = new byte[0];
            b = decoder.decodeBuffer(baseStrs[1]);

            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            return new Base64Util(b, baseStrs[0]);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * MultipartFile 转 File
     *
     * @param file
     * @throws Exception
     */
    public static File multipartFileToFile(String base64, String fileName, String savePath) throws Exception {

        File file = null;
        //创建文件目录
        String filePath = savePath;
        File dir = new File(filePath);
        if (!dir.exists() && !dir.isDirectory()) {
            dir.mkdirs();
        }
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        try {
            String partSeparator = ",";
            if (base64.contains(partSeparator)) {
                String encodedImg = base64.split(partSeparator)[1];
                byte[] decodedImg = Base64.getDecoder().decode(encodedImg.getBytes(StandardCharsets.UTF_8));
                file = new File(filePath + fileName);
                fos = new FileOutputStream(file);
                bos = new BufferedOutputStream(fos);
                bos.write(decodedImg);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file;
    }

    //获取流文件
    private static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除本地临时文件
     *
     * @param file
     */
    public static void deleteTempFile(File file) {
        if (file != null) {
            File del = new File(file.toURI());
            del.delete();
        }
    }
}